package month1;

import java.util.*;

public class permutations46_06 {
    public static void main(String[] args) {
        System.out.println(permute(new int[]{1, 2, 3}));
    }

    static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        traceback(nums, new ArrayList<>(), ret, new boolean[nums.length]);
        return ret;
    }

    /**
     * 金典回溯吧
     * @param nums
     * @param tmp
     * @param ret
     * @param visited
     */
    static void traceback(int[] nums, List<Integer> tmp, List<List<Integer>> ret, boolean[] visited) {
        if (tmp.size() == nums.length) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = 0; i < nums.length; ++i) {
            if (!visited[i]) {
                visited[i] = true;
                tmp.add(nums[i]);
                traceback(nums, tmp, ret, visited);
                tmp.remove(tmp.size() - 1);
                visited[i] = false;
            }
        }
    }
}
